<template>
  <div class="student-platform">
    <!-- 背景渐变层 -->
    <div class="background-gradient"></div>
    <NavBar />

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 页面标题和操作 -->
      <div class="page-header">
        <div class="page-title-section">
          <h2 class="page-title">我的班级</h2>
          <div class="class-count-info">
            <span class="count-text">我加入的班级数量: </span>
            <span class="count-number">{{ filteredClassData.length }}</span>
          </div>
        </div>

        <div class="page-actions">
          <!-- 搜索按钮和搜索框 -->
          <div class="search-section">
            <!-- 搜索按钮 -->
            <button
                v-if="!showSearchInput"
                @click.stop="toggleSearch"
                @mousedown.stop
                class="search-btn"
                title="搜索班级"
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="11" cy="11" r="8"/>
                <path d="m21 21-4.35-4.35"/>
              </svg>
            </button>

            <!-- 调试信息 (可以删除) -->
            <!-- <div style="font-size: 12px; color: red;">showSearchInput: {{ showSearchInput }}</div> -->

            <!-- 搜索输入框 -->
            <div v-if="showSearchInput" class="search-container">
              <div class="search-input-wrapper">
                <input
                    ref="searchInput"
                    v-model="searchKeyword"
                    type="text"
                    class="search-input"
                    placeholder="搜索班级名称或教师姓名..."
                    @input="handleSearch"
                    @keyup.esc="closeSearch"
                    @keyup.enter="handleSearch"
                />
                <div class="search-icon">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <circle cx="11" cy="11" r="8"/>
                    <path d="m21 21-4.35-4.35"/>
                  </svg>
                </div>
                <button
                    v-if="searchKeyword"
                    @click="clearSearch"
                    class="search-clear"
                    title="清除搜索"
                >
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="18" y1="6" x2="6" y2="18"/>
                    <line x1="6" y1="6" x2="18" y2="18"/>
                  </svg>
                </button>
                <button
                    @click="closeSearch"
                    class="search-close"
                    title="关闭搜索"
                >
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="18" y1="6" x2="6" y2="18"/>
                    <line x1="6" y1="6" x2="18" y2="18"/>
                  </svg>
                </button>
              </div>
            </div>
          </div>

          <button class="join-class-btn" @click="showJoinClassModal">
            + 加入班级
          </button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p class="loading-text">正在加载班级信息...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <p class="error-text">{{ error }}</p>
        <button class="retry-btn" @click="fetchClassData">重试</button>
      </div>

      <!-- 空状态 -->
      <div v-else-if="classData.length === 0" class="empty-container">
        <div class="empty-icon">📚</div>
        <p class="empty-text">您还没有加入任何班级</p>
        <button class="empty-btn" @click="showJoinClassModal">立即加入班级</button>
      </div>

      <!-- 搜索无结果状态 -->
      <div v-else-if="filteredClassData.length === 0" class="empty-container">
        <div class="empty-icon">🔍</div>
        <p class="empty-text">没有找到匹配"{{ searchKeyword }}"的班级</p>
        <button class="empty-btn" @click="clearSearch">清空搜索条件</button>
      </div>

      <!-- 班级卡片网格 -->
      <div v-else class="class-grid">
        <div
            v-for="(classItem, index) in paginatedClassData"
            :key="index"
            class="class-card"
        >
          <div class="card-header">
            <div class="class-info">
              <h3 class="class-name">{{ classItem.name }}</h3>
              <p class="teacher-name">{{ classItem.teacher || '暂无教师信息' }}</p>
              <p class="course-code">班级ID: {{ classItem.classId }}</p>
              <p class="class-description">{{ classItem.description || '暂无班级描述' }}</p>
            </div>
            <div class="class-icon">
              <div class="course-icon"></div>
            </div>
          </div>

          <div class="card-content">
            <div class="card-footer">
              <span class="class-size">班级人数: {{ typeof classItem.studentCount === 'number' ? classItem.studentCount : '未知' }}</span>
              <div class="card-actions">
                <button class="exit-btn" @click="showExitClassModal(classItem)" title="退出班级">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M16 17l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/>
                  </svg>
                  退出
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页组件 -->
      <div v-if="filteredClassData.length > 0" class="pagination-container">
        <div class="pagination-info">
          <span class="pagination-text">
            共 {{ filteredClassData.length }} 条记录，第 {{ pagination.currentPage }} / {{ totalPages }} 页
            <span v-if="searchKeyword" class="search-result-info">
              (搜索 "{{ searchKeyword }}" 的结果)
            </span>
          </span>
        </div>

        <div class="pagination-right">
          <!-- 页大小选择器 -->
          <div class="page-size-selector">
            <span class="page-size-label">每页显示:</span>
            <select
                v-model="pagination.pageSize"
                @change="handlePageSizeChange"
                class="page-size-select"
            >
              <option
                  v-for="size in pagination.pageSizeOptions"
                  :key="size"
                  :value="size"
              >
                {{ size }} 条
              </option>
            </select>
          </div>

          <div class="pagination-controls">
            <!-- 上一页按钮 -->
            <button
                class="pagination-btn"
                :class="{ disabled: pagination.currentPage === 1 }"
                @click="goToPage(pagination.currentPage - 1)"
                :disabled="pagination.currentPage === 1"
            >
              上一页
            </button>

            <!-- 第一页 -->
            <button
                v-if="visiblePages[0] > 1"
                class="pagination-btn page-number"
                @click="goToPage(1)"
            >
              1
            </button>

            <!-- 省略号 -->
            <span v-if="visiblePages[0] > 2" class="pagination-ellipsis">...</span>

            <!-- 页码按钮 -->
            <button
                v-for="page in visiblePages"
                :key="page"
                class="pagination-btn page-number"
                :class="{ active: page === pagination.currentPage }"
                @click="goToPage(page)"
            >
              {{ page }}
            </button>

            <!-- 省略号 -->
            <span v-if="visiblePages[visiblePages.length - 1] < totalPages - 1" class="pagination-ellipsis">...</span>

            <!-- 最后一页 -->
            <button
                v-if="visiblePages[visiblePages.length - 1] < totalPages"
                class="pagination-btn page-number"
                @click="goToPage(totalPages)"
            >
              {{ totalPages }}
            </button>

            <!-- 下一页按钮 -->
            <button
                class="pagination-btn"
                :class="{ disabled: pagination.currentPage === totalPages }"
                @click="goToPage(pagination.currentPage + 1)"
                :disabled="pagination.currentPage === totalPages"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </main>

    <!-- 加入班级弹窗 -->
    <div v-if="showJoinModal" class="modal-overlay" @click="closeJoinModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">加入班级</h3>
          <button class="modal-close" @click="closeJoinModal">
            <span class="close-icon">×</span>
          </button>
        </div>

        <div class="modal-body">
          <div class="form-group">
            <label class="form-label">邀请码</label>
            <input
                v-model="inviteCode"
                type="text"
                class="form-input"
                placeholder="请输入6位邀请码（例如：mK9pL2）"
                :disabled="joinLoading"
                @keyup.enter="joinClassByCode"
                @input="validateInviteCode"
                maxlength="6"
            />
            <div class="form-hint">
              邀请码为6位字符，仅支持特定字符集（例如：mK9pL2）
            </div>
          </div>

          <div v-if="joinError" class="error-message">
            {{ joinError }}
          </div>

          <div v-if="joinSuccess" class="success-message">
            {{ joinSuccess }}
          </div>
        </div>

        <div class="modal-footer">
          <button class="cancel-btn" @click="closeJoinModal" :disabled="joinLoading">
            取消
          </button>
          <button
              class="confirm-btn"
              @click="joinClassByCode"
              :disabled="joinLoading || !isInviteCodeValid()"
          >
            <span v-if="joinLoading" class="loading-spinner-small"></span>
            {{ joinLoading ? '加入中...' : '确认加入' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 退出班级确认弹窗 -->
    <div v-if="showExitModal" class="modal-overlay" @click="closeExitModal">
      <div class="modal-content exit-modal" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">退出班级确认</h3>
          <button class="modal-close" @click="closeExitModal">
            <span class="close-icon">×</span>
          </button>
        </div>

        <div class="modal-body">
          <div class="exit-warning">
            <div class="warning-icon">
              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#EF4444" stroke-width="2">
                <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L4.268 19.5c-.77.833.192 2.5 1.732 2.5z"/>
              </svg>
            </div>
            <div class="warning-content">
              <p class="warning-title">确定要退出班级吗？</p>
              <div v-if="exitingClass" class="exit-class-info">
                <p class="exit-class-name">班级名称：{{ exitingClass.name }}</p>
                <p class="exit-class-teacher">授课教师：{{ exitingClass.teacher || '暂无教师信息' }}</p>
                <p class="exit-class-id">班级ID：{{ exitingClass.classId }}</p>
              </div>
              <p class="warning-desc">退出后您将无法再访问该班级的相关内容，如需重新加入请联系教师获取邀请码。</p>
            </div>
          </div>

          <div v-if="exitError" class="error-message">
            {{ exitError }}
          </div>
        </div>

        <div class="modal-footer">
          <button class="cancel-btn" @click="closeExitModal" :disabled="exitLoading">
            取消
          </button>
          <button
              class="exit-confirm-btn"
              @click="confirmExitClass"
              :disabled="exitLoading"
          >
            <span v-if="exitLoading" class="loading-spinner-small"></span>
            {{ exitLoading ? '退出中...' : '确认退出' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import NavBar from "@/components/NavBar.vue";

// 获取用户ID的逻辑
const getCurrentStudentId = () => {
  try {
    const storedId = localStorage.getItem('id')
    console.log('从localStorage获取的ID:', storedId)

    if (storedId && storedId !== 'null' && storedId !== 'undefined') {
      const parsedId = parseInt(storedId, 10)
      if (!isNaN(parsedId) && parsedId > 0) {
        console.log('获取到有效的用户ID:', parsedId)
        return parsedId
      }
    }

    console.log('使用默认用户ID: 6')
    return 6
  } catch (error) {
    console.error('获取localStorage中的用户ID失败:', error)
    console.log('使用默认用户ID: 6')
    return 6
  }
}

// 确保用户数据在localStorage中正确保存
const ensureUserDataInStorage = () => {
  try {
    const currentId = currentStudentId.value || userInfo.id
    const currentUsername = userInfo.username
    
    console.log('确保用户数据存储，当前数据:', {
      currentStudentId: currentStudentId.value,
      userInfoId: userInfo.id,
      username: currentUsername
    })
    
    // 确保ID存在于localStorage
    if (currentId) {
      const storedId = localStorage.getItem('id')
      if (storedId !== currentId.toString()) {
        localStorage.setItem('id', currentId.toString())
        console.log('更新localStorage中的ID:', currentId)
      }
    }
    
    // 确保用户名存在于localStorage
    if (currentUsername) {
      const storedUsername = localStorage.getItem('username')
      if (storedUsername !== currentUsername) {
        localStorage.setItem('username', currentUsername)
        console.log('更新localStorage中的用户名:', currentUsername)
      }
    }
    
    // 验证存储结果
    const verification = {
      id: localStorage.getItem('id'),
      username: localStorage.getItem('username')
    }
    console.log('localStorage验证结果:', verification)
    
    return verification
  } catch (error) {
    console.error('确保用户数据存储失败:', error)
    return null
  }
}

// 响应式数据
const router = useRouter()
const currentStudentId = ref(getCurrentStudentId())
const searchInput = ref(null)

// 用户信息
const userInfo = reactive({
  id: null,
  username: null
})

// 状态管理
const loading = ref(false)
const error = ref(null)

// 加入班级弹窗相关
const showJoinModal = ref(false)
const inviteCode = ref('')
const joinLoading = ref(false)
const joinError = ref(null)
const joinSuccess = ref(null)

// 搜索相关
const searchKeyword = ref('')
const showSearchInput = ref(false)

// 退出班级弹窗相关
const showExitModal = ref(false)
const exitingClass = ref(null)
const exitLoading = ref(false)
const exitError = ref(null)

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 6,
  pageSizeOptions: [6, 12, 18, 24, 30]
})

const navTabs = reactive([
  { name: '教学管理中心', active: true },
  { name: '个人信息中心', active: false },
  { name: 'AI资源中心', active: false }
])

const classData = ref([])

// 计算属性
const filteredClassData = computed(() => {
  if (!searchKeyword.value.trim()) {
    return classData.value
  }

  const keyword = searchKeyword.value.toLowerCase().trim()
  return classData.value.filter(classItem => {
    // 按班级名称搜索
    const className = (classItem.name || '').toLowerCase()
    const classNameMatch = className.includes(keyword)

    // 按教师姓名搜索
    const teacherName = (classItem.teacher || '').toLowerCase()
    const teacherNameMatch = teacherName.includes(keyword)

    // 也支持按班级ID搜索（可选）
    const classId = (classItem.classId || '').toString().toLowerCase()
    const classIdMatch = classId.includes(keyword)

    return classNameMatch || teacherNameMatch || classIdMatch
  })
})

// 计算当前页显示的数据
const paginatedClassData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredClassData.value.slice(start, end)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredClassData.value.length / pagination.pageSize)
})

// 计算显示的页码范围
const visiblePages = computed(() => {
  const current = pagination.currentPage
  const total = totalPages.value
  const delta = 2 // 当前页前后显示的页数

  let start = Math.max(1, current - delta)
  let end = Math.min(total, current + delta)

  // 如果开始页码距离1较远，确保显示足够的页码
  if (end - start < 2 * delta) {
    if (start === 1) {
      end = Math.min(total, start + 2 * delta)
    } else if (end === total) {
      start = Math.max(1, end - 2 * delta)
    }
  }

  const pages = []
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

// 方法
const updateStudentId = async (newId) => {
  try {
    if (newId && !isNaN(parseInt(newId, 10))) {
      localStorage.setItem('id', newId.toString())
      currentStudentId.value = parseInt(newId, 10)
      console.log('用户ID已更新为:', currentStudentId.value)

      // 重新获取用户信息和班级数据
      await fetchUserInfo()
      await fetchClassData()
      
      // 确保更新后的数据在localStorage中正确保存
      ensureUserDataInStorage()
    } else {
      console.error('无效的用户ID:', newId)
    }
  } catch (error) {
    console.error('更新用户ID失败:', error)
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/users/${currentStudentId.value}`)

    if (response.data.code === 200 && response.data.data) {
      Object.assign(userInfo, {
        id: response.data.data.id,
        username: response.data.data.username
      })
      
      // 获取用户信息后，确保localStorage中的数据是最新的
      ensureUserDataInStorage()
    } else {
      console.error('获取用户信息失败:', response.data.message || '未知错误')
      // 设置默认值或错误提示
      Object.assign(userInfo, {
        id: currentStudentId.value,
        username: '用户信息获取失败'
      })
    }
  } catch (error) {
    console.error('获取用户信息请求失败:', error)
    // 设置默认值
    Object.assign(userInfo, {
      id: currentStudentId.value,
      username: '无法获取用户信息'
    })
  }
}

const setActiveTab = (index) => {
  navTabs.forEach((tab, i) => {
    tab.active = i === index
  })
}

const showJoinClassModal = () => {
  showJoinModal.value = true
  inviteCode.value = ''
  joinError.value = null
  joinSuccess.value = null
}

const closeJoinModal = () => {
  showJoinModal.value = false
  inviteCode.value = ''
  joinError.value = null
  joinSuccess.value = null
  joinLoading.value = false
}

// 验证邀请码格式
const validateInviteCode = () => {
  // 后端允许的字符集
  const allowedChars = "mK9pL2qR5sT8uV1wX4yZ7aB0cD3eF6gH9jN"

  // 只保留允许的字符，最多6位
  let filtered = ''
  for (let char of inviteCode.value) {
    if (allowedChars.includes(char) && filtered.length < 6) {
      filtered += char
    }
  }
  inviteCode.value = filtered
}

// 检查邀请码格式是否正确
const isInviteCodeValid = () => {
  const code = inviteCode.value.trim()
  const allowedChars = "mK9pL2qR5sT8uV1wX4yZ7aB0cD3eF6gH9jN"

  // 检查长度和字符有效性
  if (code.length !== 6) return false

  for (let char of code) {
    if (!allowedChars.includes(char)) return false
  }

  return true
}

// 通过邀请码加入班级
const joinClassByCode = async () => {
  const trimmedCode = inviteCode.value.trim()

  if (!trimmedCode) {
    joinError.value = '请输入邀请码'
    return
  }

  if (!isInviteCodeValid()) {
    joinError.value = '邀请码格式不正确，请输入6位有效字符组合'
    return
  }

  joinLoading.value = true
  joinError.value = null
  joinSuccess.value = null

  try {
    // 使用URLSearchParams发送表单数据
    const params = new URLSearchParams()
    params.append('inviteCode', trimmedCode)
    params.append('studentId', currentStudentId.value)

    const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/api/class-students/getInClassByInviteCode`, params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })

    if (response.data.code === 200) {
      joinSuccess.value = '成功加入班级！'

      // 延迟关闭弹窗并刷新数据
      setTimeout(async () => {
        closeJoinModal()
        resetPagination() // 重置分页到第一页
        await fetchClassData() // 刷新班级列表
      }, 1500)
    } else {
      joinError.value = response.data.message || '加入班级失败'
    }
  } catch (error) {
    console.error('加入班级失败:', error)
    if (error.response && error.response.data && error.response.data.message) {
      joinError.value = error.response.data.message
    } else {
      joinError.value = '加入班级失败，请检查邀请码是否正确'
    }
  } finally {
    joinLoading.value = false
  }
}

// 分页相关方法
const goToPage = (page) => {
  if (page < 1 || page > totalPages.value || page === pagination.currentPage) {
    return
  }
  pagination.currentPage = page
}

const resetPagination = () => {
  pagination.currentPage = 1
}

// 处理页大小变化
const handlePageSizeChange = () => {
  // 重置到第一页
  pagination.currentPage = 1
}

// 搜索相关方法
const handleSearch = () => {
  // 搜索时重置到第一页
  pagination.currentPage = 1
  // 可以添加调试信息
  console.log('搜索关键词:', searchKeyword.value)
  console.log('搜索结果数量:', filteredClassData.value.length)
}

const clearSearch = () => {
  searchKeyword.value = ''
  pagination.currentPage = 1
  console.log('已清空搜索条件')
}

const toggleSearch = () => {
  console.log('点击了搜索按钮')
  console.log('当前showSearchInput状态:', showSearchInput.value)
  showSearchInput.value = true
  console.log('设置后showSearchInput状态:', showSearchInput.value)
  // 等待DOM更新后聚焦输入框
  nextTick(() => {
    console.log('DOM更新后的状态')
    if (searchInput.value) {
      searchInput.value.focus()
      console.log('搜索输入框已聚焦')
    } else {
      console.log('未找到搜索输入框元素')
    }
  })
}

// 测试方法 - 可以在浏览器控制台调用
const testToggleSearch = () => {
  console.log('测试方法被调用')
  showSearchInput.value = !showSearchInput.value
  console.log('测试后showSearchInput状态:', showSearchInput.value)
}

const closeSearch = () => {
  showSearchInput.value = false
  searchKeyword.value = ''
  pagination.currentPage = 1
}

// 处理点击外部区域关闭搜索框
const handleClickOutside = (event) => {
  // 如果搜索输入框没有显示，不需要处理
  if (!showSearchInput.value) {
    return
  }

  const searchSection = document.querySelector('.search-section')
  if (searchSection && !searchSection.contains(event.target)) {
    // 只有在没有搜索关键词时才关闭搜索框
    if (!searchKeyword.value) {
      console.log('点击外部区域，关闭搜索框')
      closeSearch()
    }
  }
}

// 退出班级相关方法
const showExitClassModal = (classItem) => {
  exitingClass.value = classItem
  showExitModal.value = true
  exitError.value = null
}

const closeExitModal = () => {
  showExitModal.value = false
  exitingClass.value = null
  exitError.value = null
  exitLoading.value = false
}

const confirmExitClass = async () => {
  if (!exitingClass.value) {
    return
  }

  exitLoading.value = true
  exitError.value = null

  try {
    // 使用URLSearchParams发送表单数据
    const params = new URLSearchParams()
    params.append('classId', exitingClass.value.classId)
    params.append('studentId', currentStudentId.value)

    const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/api/class-students/deleteClassStudents`, params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })

    if (response.data.code === 200) {
      // 退出成功
      closeExitModal()

      // 显示成功提示（可以添加toast组件，这里暂时用console）
      console.log('退出班级成功')

      // 重新获取班级数据
      await fetchClassData()

      // 如果当前页没有数据了，回到上一页
      if (paginatedClassData.value.length === 0 && pagination.currentPage > 1) {
        pagination.currentPage -= 1
      }
    } else {
      exitError.value = response.data.message || '退出班级失败'
    }
  } catch (error) {
    console.error('退出班级失败:', error)
    if (error.response && error.response.data && error.response.data.message) {
      exitError.value = error.response.data.message
    } else {
      exitError.value = '退出班级失败，请稍后重试'
    }
  } finally {
    exitLoading.value = false
  }
}

// 获取学生已加入的班级数据
const fetchClassData = async () => {
  loading.value = true
  error.value = null

  try {
    // 1. 获取学生已加入的班级列表
    const classStudentsResponse = await axios.get(
        `${import.meta.env.VITE_API_BASE_URL}/api/class-students/getClassStudentsByClassId?studentId=${currentStudentId.value}`
    )

    if (classStudentsResponse.data.code !== 200) {
      throw new Error(classStudentsResponse.data.message || '获取班级列表失败')
    }

    const classStudents = classStudentsResponse.data.data

    if (!classStudents || classStudents.length === 0) {
      classData.value = []
      return
    }

    // 2. 并行获取每个班级的详细信息和真实学生人数
    const classDetailsPromises = classStudents.map(async (classStudent) => {
      try {
        // 并行获取班级详情和班级人数
        const [classResponse, studentCountResponse] = await Promise.all([
          axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/classes/getClassById?classId=${classStudent.classId}`),
          axios.post(`${import.meta.env.VITE_API_BASE_URL}/api/class-teachers/getClassesStudentByClassId?classId=${classStudent.classId}`)
        ])

        if (classResponse.data.code === 200) {
          const classDetail = classResponse.data.data

          // 计算班级人数
          let studentCount = 0
          if (studentCountResponse.data.code === 200 && Array.isArray(studentCountResponse.data.data)) {
            studentCount = studentCountResponse.data.data.length
          }

          // 获取教师信息
          let teacherName = '暂无教师信息'
          try {
            // 先根据班级ID获取教师ID
            const teacherIdResponse = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/classes/getTeacherIdByClassId?classId=${classStudent.classId}`)

            if (teacherIdResponse.data.code === 200 && teacherIdResponse.data.data) {
              const teacherId = teacherIdResponse.data.data

              // 再根据教师ID获取教师用户信息
              const teacherInfoResponse = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/users/${teacherId}`)

              if (teacherInfoResponse.data.code === 200 && teacherInfoResponse.data.data) {
                const teacherInfo = teacherInfoResponse.data.data
                teacherName = teacherInfo.username || '暂无教师信息'
              }
            }
          } catch (teacherError) {
            console.error(`获取班级 ${classStudent.classId} 教师信息失败:`, teacherError)
            // 如果获取教师信息失败，使用默认值
          }

          return {
            classId: classDetail.classId,
            name: classDetail.name,
            description: classDetail.description,
            teacher: teacherName, // 使用获取到的教师用户名
            code: `CLASS${classDetail.classId}`,
            studentCount: studentCount, // 使用真实的学生人数
            createdAt: classDetail.createdAt,
            originalData: classDetail
          }
        }
        return null
      } catch (error) {
        console.error(`获取班级 ${classStudent.classId} 详情失败:`, error)
        return null
      }
    })

    // 3. 等待所有班级详情请求完成
    const classDetails = await Promise.all(classDetailsPromises)

    // 4. 过滤掉获取失败的班级
    classData.value = classDetails.filter(classDetail => classDetail !== null)

  } catch (error) {
    console.error('获取班级数据失败:', error)
    error.value = error.message || '获取班级数据失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(async () => {
  // 记录当前使用的用户ID
  console.log('当前使用的学生ID:', currentStudentId.value)
  
  // 确保用户数据在localStorage中正确保存
  ensureUserDataInStorage()

  // 先获取用户信息，再获取班级数据
  await fetchUserInfo()
  await fetchClassData()
  
  // 添加点击外部区域关闭搜索框的监听器
  document.addEventListener('click', handleClickOutside)

  // 调试信息
  console.log('组件已挂载，showSearchInput初始状态:', showSearchInput.value)
  
  // 最终验证localStorage数据
  const finalVerification = {
    id: localStorage.getItem('id'),
    username: localStorage.getItem('username'),
    currentStudentId: currentStudentId.value,
    userInfo: userInfo
  }
  console.log('组件挂载完成，最终用户数据状态:', finalVerification)
})

onBeforeUnmount(() => {
  // 清理事件监听器
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.student-platform {
  position: fixed;
  width: 100%;
  min-height: 100vh;
  font-family: 'Inter', sans-serif;
  background: #F8FAFC;
  overflow-x: hidden;
}

/* 顶部导航栏 */
.top-navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 89px;
  background: #FFFFFF;
  border-bottom: 0.8px solid #E2E8F0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  z-index: 1000;
  box-sizing: border-box;
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 40px;
}

.platform-title {
  font-weight: 700;
  font-size: 20px;
  line-height: 28px;
  color: #1E293B;
  margin: 0;
}

.nav-tabs {
  display: flex;
  align-items: center;
  gap: 44px;
}

.nav-tab {
  font-weight: 500;
  font-size: 16px;
  line-height: 24px;
  color: #64748B;
  cursor: pointer;
  position: relative;
  padding: 8px 12px;
  transition: color 0.3s;
}

.nav-tab.active {
  color: #3B82F6;
}

.nav-tab.active::after {
  content: '';
  position: absolute;
  bottom: -30px;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  height: 1.6px;
  background: #3B82F6;
}

.nav-right {
  display: flex;
  align-items: center;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  border-radius: 8px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #E2E8F0;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  color: #1E293B;
}

.user-id {
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  color: #64748B;
}

.dropdown-icon {
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-line {
  width: 9.33px;
  height: 4.67px;
  border: 2px solid #000000;
}

/* 主内容区域 */
.main-content {
  margin-left: 0; /* 移除侧边栏留出的空间 */
  margin-top: 0px; /* 为固定的顶部导航栏留出空间 */
  padding: 35px 32px;
  min-height: 100vh;
  background: linear-gradient(90deg, #E2E8F0 10%, #F1F5F9 50%, #F8FAFC 90%);
  position: relative;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 29px;
  gap: 24px;
}

.page-title-section {
  display: flex;
  align-items: center;
  gap: 24px;
}

.page-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-weight: 700;
  font-size: 40px;
  line-height: 32px;
  color: #1E293B;
  margin: 0;
}

.class-count-info {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background: linear-gradient(90deg, #E2E8F0 20%, #F1F5F9 80%);
  border-radius: 8px;
  border: 1px solid #CBD5E1;
}

.count-text {
  font-size: 14px;
  color: #64748B;
  font-weight: 500;
}

.count-number {
  font-size: 16px;
  color: #3B82F6;
  font-weight: 700;
  margin-left: 4px;
}

/* 搜索栏样式 */
.search-section {
  position: relative;
  z-index: 10;
}

.search-btn {
  width: 40px;
  height: 40px;
  border: 1.5px solid #E2E8F0;
  border-radius: 8px;
  background: #FFFFFF;
  color: #64748B;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 11;
}

.search-btn:hover {
  border-color: #3B82F6;
  color: #3B82F6;
  background: #F8FAFC;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

.search-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.15);
}

.search-container {
  position: relative;
  animation: searchSlideIn 0.3s ease-out;
}

@keyframes searchSlideIn {
  from {
    opacity: 0;
    transform: translateX(20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateX(0) scale(1);
  }
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  width: 280px;
  height: 40px;
  padding: 0 50px 0 40px;
  border: 1.5px solid #E2E8F0;
  border-radius: 8px;
  font-size: 14px;
  color: #1E293B;
  background: #FFFFFF;
  transition: all 0.3s;
  outline: none;
}

.search-input:focus {
  border-color: #3B82F6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.search-input::placeholder {
  color: #94A3B8;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #64748B;
  pointer-events: none;
}

.search-clear {
  position: absolute;
  right: 38px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #64748B;
  cursor: pointer;
  padding: 2px;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-clear:hover {
  color: #EF4444;
  background: #FEF2F2;
}

.search-close {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #64748B;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-close:hover {
  color: #1E293B;
  background: #F1F5F9;
}

.join-class-btn {
  background: #3B82F6;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  height: 40px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-weight: 500;
  font-size: 16px;
  line-height: 24px;
  color: #FFFFFF;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.join-class-btn:hover {
  background: #2563EB;
}

/* 状态显示 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #E2E8F0;
  border-top: 4px solid #3B82F6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #64748B;
  margin: 0;
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.error-text {
  font-size: 16px;
  color: #DC2626;
  margin: 0 0 16px 0;
}

.retry-btn {
  background: #3B82F6;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  color: #FFFFFF;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.retry-btn:hover {
  background: #2563EB;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: #64748B;
  margin: 0 0 24px 0;
}

.empty-btn {
  background: #3B82F6;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  color: #FFFFFF;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.empty-btn:hover {
  background: #2563EB;
}

/* 班级网格 */
.class-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(456px, 1fr));
  gap: 24px;
  max-width: 100%;
}

.class-card {
  background: #FFFFFF;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0px 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}

.class-card:hover {
  transform: translateY(-2px);
  box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.class-info {
  flex: 1;
}

.class-name {
  font-weight: 600;
  font-size: 18px;
  line-height: 28px;
  color: #1E293B;
  margin: 0 0 8px 0;
}

.teacher-name {
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  color: #64748B;
  margin: 0 0 8px 0;
}

.course-code {
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
  color: #94A3B8;
  margin: 0 0 8px 0;
}

.class-description {
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
  color: #64748B;
  margin: 0;
  background: #F8FAFC;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 3px solid #3B82F6;
}

.class-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #F8FAFC;
}

.course-icon {
  width: 13.33px;
  height: 15px;
  border: 2px solid #000000;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.class-size {
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
  color: #64748B;
}

.exit-btn {
  background: none;
  border: 1px solid #EF4444;
  font-weight: 400;
  font-size: 12px;
  line-height: 16px;
  color: #EF4444;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.exit-btn:hover {
  background: #EF4444;
  color: #FFFFFF;
}

.exit-btn svg {
  width: 12px;
  height: 12px;
}

/* 分页组件样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 32px;
  padding: 20px 0;
  border-top: 1px solid #E2E8F0;
}

.pagination-info {
  display: flex;
  align-items: center;
}

.pagination-text {
  font-size: 14px;
  color: #64748B;
  line-height: 20px;
}

.search-result-info {
  color: #3B82F6;
  font-weight: 500;
}

.pagination-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-label {
  font-size: 14px;
  color: #64748B;
  font-weight: 500;
}

.page-size-select {
  height: 36px;
  padding: 0 12px;
  border: 1px solid #E2E8F0;
  border-radius: 6px;
  background: #FFFFFF;
  color: #374151;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  outline: none;
  min-width: 80px;
}

.page-size-select:hover {
  border-color: #3B82F6;
}

.page-size-select:focus {
  border-color: #3B82F6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-btn {
  height: 36px;
  padding: 0 12px;
  border: 1px solid #E2E8F0;
  border-radius: 6px;
  background: #FFFFFF;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 36px;
}

.pagination-btn:hover:not(.disabled):not(.active) {
  border-color: #3B82F6;
  color: #3B82F6;
  background: #F8FAFC;
}

.pagination-btn.active {
  background: #3B82F6;
  border-color: #3B82F6;
  color: #FFFFFF;
}

.pagination-btn.disabled {
  background: #F8FAFC;
  color: #9CA3AF;
  cursor: not-allowed;
  border-color: #E5E7EB;
}

.pagination-btn.page-number {
  min-width: 36px;
}

.pagination-ellipsis {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 36px;
  padding: 0 8px;
  color: #9CA3AF;
  font-size: 14px;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: #FFFFFF;
  border-radius: 12px;
  width: 90%;
  max-width: 480px;
  box-shadow: 0px 20px 24px rgba(0, 0, 0, 0.15);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 0 24px;
}

.modal-title {
  font-weight: 600;
  font-size: 20px;
  line-height: 28px;
  color: #1E293B;
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.modal-close:hover {
  background: #F1F5F9;
}

.close-icon {
  font-size: 24px;
  color: #64748B;
  line-height: 1;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  color: #374151;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  height: 44px;
  padding: 0 16px;
  border: 1.5px solid #E2E8F0;
  border-radius: 8px;
  font-size: 16px;
  line-height: 24px;
  color: #1E293B;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #3B82F6;
}

.form-input:disabled {
  background: #F8FAFC;
  color: #94A3B8;
  cursor: not-allowed;
}

.form-input::placeholder {
  color: #94A3B8;
}

.form-hint {
  font-size: 12px;
  line-height: 16px;
  color: #6B7280;
  margin-top: 6px;
}

.error-message {
  padding: 12px 16px;
  background: #FEF2F2;
  border: 1px solid #FECACA;
  border-radius: 8px;
  color: #DC2626;
  font-size: 14px;
  line-height: 20px;
  margin-top: 12px;
}

.success-message {
  padding: 12px 16px;
  background: #F0FDF4;
  border: 1px solid #BBF7D0;
  border-radius: 8px;
  color: #16A34A;
  font-size: 14px;
  line-height: 20px;
  margin-top: 12px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0 24px 24px 24px;
}

.cancel-btn {
  background: #FFFFFF;
  border: 1.5px solid #E2E8F0;
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  color: #64748B;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn:hover:not(:disabled) {
  background: #F8FAFC;
  border-color: #CBD5E1;
}

.cancel-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.confirm-btn {
  background: #3B82F6;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  color: #FFFFFF;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.confirm-btn:hover:not(:disabled) {
  background: #2563EB;
}

.confirm-btn:disabled {
  background: #94A3B8;
  cursor: not-allowed;
}

.loading-spinner-small {
  width: 16px;
  height: 16px;
  border: 2px solid #FFFFFF;
  border-top: 2px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

/* 退出班级弹窗样式 */
.exit-modal {
  max-width: 520px;
}

.exit-warning {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.warning-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #FEF2F2;
  border-radius: 50%;
}

.warning-content {
  flex: 1;
}

.warning-title {
  font-size: 18px;
  font-weight: 600;
  color: #1F2937;
  margin: 0 0 12px 0;
}

.exit-class-info {
  background: #F9FAFB;
  border: 1px solid #E5E7EB;
  border-radius: 8px;
  padding: 12px;
  margin: 12px 0;
}

.exit-class-name {
  font-size: 14px;
  font-weight: 600;
  color: #1F2937;
  margin: 0 0 4px 0;
}

.exit-class-teacher,
.exit-class-id {
  font-size: 13px;
  color: #6B7280;
  margin: 0 0 4px 0;
}

.exit-class-id {
  margin-bottom: 0;
}

.warning-desc {
  font-size: 14px;
  color: #6B7280;
  line-height: 1.5;
  margin: 8px 0 0 0;
}

.exit-confirm-btn {
  background: #EF4444;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  font-size: 14px;
  line-height: 20px;
  color: #FFFFFF;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.exit-confirm-btn:hover:not(:disabled) {
  background: #DC2626;
}

.exit-confirm-btn:disabled {
  background: #F87171;
  cursor: not-allowed;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .sidebar {
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }

  .sidebar.sidebar-open {
    transform: translateX(0);
  }

  .main-content {
    margin-left: 0;
    margin-top: 89px;
  }

  .class-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .nav-left {
    gap: 20px;
  }

  .nav-tabs {
    gap: 20px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .user-profile {
    gap: 8px;
  }

  .platform-title {
    font-size: 18px;
  }

  .main-content {
    padding: 24px 16px;
    margin-left: 0;
    margin-top: 89px;
  }

  .top-navbar {
    padding: 0 16px;
  }

  /* 移动端分页样式调整 */
  .pagination-container {
    flex-direction: column;
    gap: 16px;
    align-items: center;
  }

  .pagination-right {
    flex-direction: column;
    gap: 12px;
    align-items: center;
  }

  .pagination-controls {
    flex-wrap: wrap;
    justify-content: center;
    gap: 6px;
  }

  .pagination-btn {
    height: 32px;
    min-width: 32px;
    padding: 0 10px;
    font-size: 13px;
  }

  .pagination-ellipsis {
    height: 32px;
    padding: 0 6px;
  }

  .page-size-select {
    height: 32px;
    min-width: 100px;
    font-size: 13px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .page-title-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    width: 100%;
  }

  .page-actions {
    flex-direction: column;
    width: 100%;
    gap: 12px;
  }

  .search-section {
    width: 100%;
  }

  .search-btn {
    width: 100%;
    justify-content: center;
  }

  .search-input {
    width: 100%;
  }

  .pagination-right {
    flex-direction: column;
    gap: 12px;
    align-items: center;
  }
}

@media (max-width: 600px) {
  .nav-tabs {
    display: none;
  }

  .class-card {
    padding: 20px;
  }

  .card-header {
    margin-bottom: 24px;
  }

  .platform-title {
    font-size: 16px;
  }

  .main-content {
    padding: 20px 12px;
    margin-left: 0;
    margin-top: 89px;
  }
}
</style>